package chatdialogservicelogic

import (
	"context"
	"time"

	"paper-pro/app/chat/rpc/internal/svc"
	"paper-pro/app/chat/rpc/pb"
	delchattask "paper-pro/pkg/types"
	"paper-pro/pkg/xerr"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
)

type DeleteManyLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDeleteManyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteManyLogic {
	return &DeleteManyLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 该接口删除Assistant关联ChatDialog，删除消息由之前Assistant删除发布
func (l *DeleteManyLogic) DeleteMany(in *pb.ChatDialogDeleteManyReq) (*pb.ChatDialogDeleteManyResp, error) {
	session, err := l.svcCtx.ChatDialogModel.StartSession()
	if err != nil {
		return nil, errors.Wrapf(err, "Chat Dialog DeleteManyLogic: 事务启动失败: %v", err)
	}
	defer session.EndSession(l.ctx)

	dialogIds, err := session.WithTransaction(l.ctx, func(sessCtx mongo.SessionContext) (any, error) {
		dialogs, err := l.svcCtx.ChatDialogModel.FindMany(sessCtx, in.AssistantId, in.UserId)
		if err != nil {
			return nil, errors.Wrapf(err, "Chat Dialog DeleteManyLogic: Delete Assiatant Id: %s, User Id: %d failed. error: %v.",
				in.AssistantId, in.UserId, err)
		}
		if len(dialogs) == 0 {
			err := xerr.NewErrCode(xerr.DB_UPDATE_AFFECTED_ZERO_ERROR)
			return nil, errors.Wrapf(err, "Chat Dialog DeleteManyLogic: Delete Assiatant Id: %s, User Id: %d failed. error: %v.",
				in.AssistantId, in.UserId, err)
		}

		dialogIDs := make([]primitive.ObjectID, len(dialogs))
		for i := range dialogs {
			dialogIDs[i] = dialogs[i].ID
		}
		_, err = l.svcCtx.ChatDialogModel.DeleteMany(sessCtx, dialogIDs, in.UserId)
		if err != nil {
			return nil, errors.Wrapf(err, "Chat Dialog DeleteManyLogic: Delete Assiatant Id: %s, User Id: %d failed. Delete Dialogs failed. error %v",
				in.AssistantId, in.UserId, err)
		}

		dialogIds := make([]string, len(dialogs))
		for i := range dialogs {
			dialogIds[i] = dialogs[i].ID.Hex()
		}

		return dialogIds, nil
	})

	if err != nil {
		return nil, err
	}
	if dialogIds, ok := dialogIds.([]string); ok {
		taskPayload, err := delchattask.DelDialogsPayload(dialogIds, in.UserId)
		if err != nil {
			l.Errorf("DeleteAssistant Id: %s: delay delete chat msgs: Marshal task error: %v", in.AssistantId, err)
		}
		_, err = l.svcCtx.DqPusherClient.Delay(taskPayload, time.Minute*5)
		if err != nil {
			l.Errorf("DeleteAssistant Id: %s: delay delete chat msgs: push delay queue error: %v", in.AssistantId, err)
		}
	} else {
		l.Errorf("DeleteAssistant Id: %s: delay delete chat msgs: get delete dialogIds error: %v", in.AssistantId, err)
	}

	return &pb.ChatDialogDeleteManyResp{}, err
}
